package io.renren.modules.sys.controller;


import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import io.renren.common.config.ConstantConfig;
import io.renren.modules.sys.entity.TokenEntity;
import io.renren.common.utils.Jdpush;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import io.renren.common.annotation.Login;
import io.renren.common.utils.R;
import io.renren.modules.sys.dto.RegisterEntity;
import io.renren.modules.sys.entity.SmsEntity;
import io.renren.modules.sys.entity.UserEntity;
import io.renren.modules.sys.form.RegisterForm;
import io.renren.modules.sys.service.TokenService;
import io.renren.modules.sys.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 注册接口
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-26 17:27
 */
@RestController
@RequestMapping("/api")
@Api(tags = "注册接口")
public class ApiRegisterController {
    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;


    @PostMapping("QQBinding")
    @ApiOperation("QQ绑定")
    public R QQBinding(@RequestBody RegisterEntity registerEntity) throws UnsupportedEncodingException {
        int code = 100;
        String msg = "注册成功";
        Long userId = userService.getUserIdByMobile(registerEntity.getMobile());
        //验证验证码
        SmsEntity s = userService.getSmsEntityByCode(new SmsEntity(registerEntity.getMobile(), registerEntity.getCode()));
        UserEntity user = new UserEntity();
        user.setMobile(registerEntity.getMobile());
        //user.setPassword(DigestUtils.sha256Hex(registerEntity.getPassword()));
        user.setQqUid(registerEntity.getQqUid());
        user.setOpenId(registerEntity.getOpenId());
        user.setPassword(DigestUtils.sha256Hex(registerEntity.getPassword()));

        if (registerEntity.getNackName() != null) {
            user.setNickName(registerEntity.getNackName());
        } else {
            user.setNickName("核桃" + System.currentTimeMillis());
        }
        if (registerEntity.getSchoolName() != null) {
            user.setSchoolId(registerEntity.getSchoolId());
            user.setSchoolName(registerEntity.getSchoolName());
        }
        if (registerEntity.getHeadImg() != null) {
            user.setHeadImg(registerEntity.getHeadImg());
        } else {
            user.setHeadImg("http://106.14.146.131:280/image/NewsImg/moren.jpg");
        }

        if (registerEntity.getQqUid() != null && !"".equals(registerEntity.getQqUid())) {
            user.setIsBangDingQQ(1);
        } else if (registerEntity.getOpenId() != null && !"".equals(registerEntity.getOpenId())) {
            user.setIsBangDingWeChat(1);
        }

        UserEntity newUser;
        if (s == null) {//验证码过期或者没找到
            code = 101;
            msg = "验证码不正确或者过期";
            return R.ok(msg, code);
        } else {

            if (userId == null) {

                user.setNickNameB(user.getNickName().getBytes());
                //user.setNickName(new String(user.getNickNameB(),"utf-8"));
                // userService.updateNickNameById(user);
                user.setNickName("");
                userService.insert(user);
                newUser = userService.getNewUser();
                user.setNickName(new String(user.getNickNameB(), "utf-8"));
                user.setUserId(newUser.getUserId());
            } else {
                user.setUserId(userId);
                userService.updateById(user);
            }
            TokenEntity token = tokenService.createToken(user.getUserId());
            Map<String, Object> map = new HashMap<>(2);
            map.put("token", token);
            map.put("isAuthentication", user.getIsAuthentication());
            map.put("expire", token.getExpireTime().getTime() - System.currentTimeMillis());
            return R.ok("绑定成功", 100)
                    .put("data", map);
        }
    }

    @PostMapping("register")
    @ApiOperation("注册")
    public R register(@RequestBody RegisterEntity registerEntity) {
        int code = 100;
        String msg = "注册成功";

        //验证验证码
        SmsEntity s = userService.getSmsEntityByCode(new SmsEntity(registerEntity.getMobile(), registerEntity.getCode()));
        UserEntity user = new UserEntity();
        user.setMobile(registerEntity.getMobile());
        user.setPassword(DigestUtils.sha256Hex(registerEntity.getPassword()));
        user.setQqUid(registerEntity.getQqUid());
        user.setOpenId(registerEntity.getOpenId());
        if (registerEntity.getSchoolName() != null) {
            user.setSchoolId(registerEntity.getSchoolId());
            user.setSchoolName(registerEntity.getSchoolName());
        }
        if (registerEntity.getNackName() == null || "".equals(registerEntity.getNackName())) {
            String nickname = "小核桃" + System.currentTimeMillis();
            user.setNickName("小核桃" + System.currentTimeMillis());
            user.setNickNameB(nickname.getBytes());
        } else {
            //user.setNickName(registerEntity.getNackName());
            user.setNickNameB(registerEntity.getNackName().getBytes());
        }
        if (registerEntity.getHeadImg() == null || "".equals(registerEntity.getHeadImg())) {
            user.setHeadImg("http://106.14.146.131:280/image/NewsImg/moren.jpg");
        } else {
            user.setHeadImg(registerEntity.getHeadImg());
        }
        if (s == null) {//验证码过期或者没找到
            code = 101;
            msg = "验证码不正确或者过期";
        } else {
            UserEntity u = userService.queryByMobile(registerEntity.getMobile());
            if (u != null) {
                code = 102;
                msg = "手机号已注册";
            } else {
                userService.insert(user);
            }
        }
        return R.ok(msg, code);
    }

    @PostMapping("verificationMobile")
    @ApiOperation("验证手机号")
    public R verificationMobile(@RequestBody RegisterForm form) {
        String mobile = form.getMobile();
        UserEntity user = userService.queryByMobile(mobile);
        int code = 100;
        String msg;
        if (user != null) {
            msg = "您的手机已注册过";
            code = 101;
        } else {
            msg = "可以注册";
            userService.sendSms(mobile);
        }
        return R.ok(msg, code);
    }


    @PostMapping("findMobile")
    @ApiOperation("根据验证码寻找手机")
    public R findMobile(@RequestBody SmsEntity smsEntity) {
        SmsEntity s = userService.getSmsEntityByCode(smsEntity);
        String msg;
        int isExpiry = 0;
        if (s == null) {
            msg = "您的验证码已过期";
            isExpiry = 1;
        } else {
            msg = "验证码未过期";
        }
        return R.ok(msg).put("isExpiry", isExpiry);
    }


    @PostMapping("update")
    @Login
    @ApiOperation("修改用户资料")
    public R update(@RequestBody UserEntity user, HttpServletRequest request) {
        user.setUserId((Long) request.getAttribute("userId"));
        userService.updateById(user);
        return R.ok("修改成功", 100);
    }

    //通过token来获取userId
    @PostMapping("getUserIdByToken")
    @ApiOperation("根据用户的token获取用户的userId")
    public Long getUserIdByToken(@RequestBody UserEntity user) {

        Long userId = tokenService.getUserIdByToken(user.getToken());
        return userId;
    }

    //比对输入的手机号和数据库中的手机号
   /* @GetMapping("selectMobile")
    //@Login
    @ApiOperation("比对输入的手机号和数据库中的手机号")
    public boolean selectMobile(@RequestParam String token,String mobile){

        Long userId = tokenService.getUserIdByToken(token);
        String mobileInSQL = userService.selectMobileByUserId(userId);
        if(mobile.equals(mobileInSQL)){
            return true;
        }
        return false;
    }*/

    /**
     * 发送验证码
     */
    @GetMapping("sendYanZhengMa")
    @ApiOperation("发送验证码")
    public R sendYanZhengMa(@RequestParam String mobile) {
        userService.sendSms(mobile);
        return R.ok("验证码发送成功", 100);
    }

    /**
     * 在登录状态下修改手机号
     */
    @PostMapping("updateMobile")
    //@Login
    @ApiOperation("在登录状态下修改手机号")
    public R updateMobile(@RequestBody UserEntity userEntity) {

        Long userId = tokenService.getUserIdByToken(userEntity.getToken());
        //newCode是前台传来的用户输入的验证码 code是短信发送的验证码
        String code = userService.getCodeByMobile(userEntity.getNewMobile());
        if (userEntity.getNewCode().equals(code)) {
            //验证码比对成功
            //判断前台传来的密码是否相同
            String passwordInSQL = userService.selectPasswordByUserId(userId);
            String passwordInUp = DigestUtils.sha256Hex(userEntity.getPassword());
            if (passwordInUp.equals(passwordInSQL)) {
                //判断输入的新手机号是否已经被注册
                List<UserEntity> users = userService.selectUserByMobile(userEntity.getNewMobile());
                if (users.size() == 0) {
                    //说明需要绑定的手机号没有被注册过 进行修改当前用户的手机号操作
                    UserEntity user = new UserEntity();
                    user.setMobile(userEntity.getNewMobile());
                    user.setUserId(userId);
                    userService.updateMobileByUserId(user);
                } else {
                    //需要绑定的手机号已经被注册过
                    return R.error(101, "该手机号已经被注册过");
                }
                return R.ok("手机号修改成功", 100);
            }
            return R.error(101, "登录密码有误");
        } else {
            //验证码比对失败
            return R.error(101, "验证码错误");
        }
    }


    @PostMapping("updateUserName")
    @Login
    @ApiOperation("通过token修改用户名username")
    public R updateUserName(@RequestBody UserEntity userEntity) throws UnsupportedEncodingException {
    	/*if(!userEntity.getUsername().equals(null)) {
    		long userId = tokenService.getUserIdByToken(userEntity.getToken());
    		UserEntity u = new UserEntity();
    		u.setUserId(userId);
    		u.setUsername(userEntity.getUsername());
    		System.out.println("当前对象:"+u);
        	userService.upadateUserNameByUserId(u);
        	return R.ok("用户名修改成功",100);
    	}
        return R.error(101,"修改的用户名不能为空");*/
        userEntity.setUserId(tokenService.getUserIdByToken(userEntity.getToken()));
        UserEntity user = userService.getUserByUserId(userEntity.getUserId());
        if (userEntity.getNickName() != null) {
            userEntity.setNickNameB(userEntity.getNickName().getBytes());
            userService.updateNickNameB(userEntity);
            //  userService.updateNickNameById(userEntity);
            return R.ok("昵称修改成功", 100);
        }
        return R.error(101, "修改的昵称不能为空");
    }


    //通过token修改性别sex
    @PostMapping("updateSex")
    @Login
    @ApiOperation("通过token修改性别sex")
    public R updateSex(@RequestBody UserEntity userEntity) {
        if (userEntity.getSex() != null) {
            long userId = tokenService.getUserIdByToken(userEntity.getToken());
            System.out.println("userId是:" + userId);
            UserEntity u = new UserEntity();
            u.setUserId(userId);
            u.setSex(userEntity.getSex());
            userService.upadateSexByUserId(u);
            return R.ok("性别修改成功", 100);
        }
        return R.error().put("修改的性别不能为空", "请重新输入");
    }


    //通过token修改年龄age
    @PostMapping("updateAge")
    @Login
    @ApiOperation("通过token修改年龄age")
    public R updateAge(@RequestBody UserEntity userEntity) {
        if (userEntity.getAge() != null) {
            long userId = tokenService.getUserIdByToken(userEntity.getToken());
            UserEntity u = new UserEntity();
            u.setUserId(userId);
            u.setAge(userEntity.getAge());
            System.out.println("当前对象:" + u);
            userService.upadateAgeByUserId(u);
            return R.ok("年龄修改成功", 100);
        }
        return R.error().put("修改的年龄不能为空", "请重新输入");
    }


    //通过token修改地址或联系方式address
    @PostMapping("updateAddress")
    @Login
    @ApiOperation("通过token修改地址address")
    public R updateAddress(@RequestBody UserEntity userEntity) {
        if (userEntity.getAddress() != null) {
            long userId = tokenService.getUserIdByToken(userEntity.getToken());
            UserEntity u = new UserEntity();
            u.setUserId(userId);
            u.setAddress(userEntity.getAddress());
            System.out.println("当前对象:" + u);
            userService.upadateAddressByUserId(u);
            return R.ok("地址修改成功", 100);
        }
        return R.error().put("修改的地址不能为空", "请重新输入");
    }

    //通过token修改头像head_image

    /**
     * 用户头像上传
     */
    @PostMapping("updateHeadImage")
    public R updateHeadImage(@RequestParam String token, MultipartFile file, HttpServletRequest request) throws IOException {
        String path = request.getSession().getServletContext().getRealPath("image");
        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        File dir = new File(path + "\\" + fileName);
        System.out.println(path);

        if (!dir.exists()) {
            dir.mkdirs();
        }
        //MultipartFile自带的解析方法
        file.transferTo(dir);

        /*Long userId = tokenService.getUserIdByToken(token);
        String headImageLocation = path+"\\"+fileName;
        UserEntity user = new UserEntity();
        user.setUserId(userId);
        user.setHeadImg(headImageLocation);
        userService.updateHeadImageByUserId(user);*/
        return R.ok("头像上传成功", 200);
    }


    /**
     * 判断是否绑定手机号
     */
    @PostMapping("selectIsBindingMobileByToken")
    @Login
    @ApiOperation("设置是否绑定手机号")
    public Boolean selectIsBindingMobileByToken(@RequestBody UserEntity userEntity) {

        Long userId = tokenService.getUserIdByToken(userEntity.getToken());
        String mobile = userService.selectMobileByUserId(userId);
        if (mobile.equals(userEntity.getNewMobile())) {
            return true;
        }
        return false;
    }

    @Autowired
    JPushController jPushController;

    /**
     * 通过token修改密码password 方式一 加上@Login注解 比对前台传的密码和数据库中的密码
     */
    @PostMapping("updatePasswordOnLogin")
    @Login
    @ApiOperation("登录状态下修改密码password")
    public R updatePassword(@RequestBody UserEntity userEntity) {
        if (userEntity.getPassword() != null) {
            Long userId = (tokenService.getUserIdByToken(userEntity.getToken()));
            //通过userId获取用户的密码
            String oldMD5Password = userService.selectPasswordByUserId(userId);
            System.out.println("加密后的用户密码是：" + oldMD5Password);
            //获取前台传来的密码并进行加密
            String MD5Password = DigestUtils.sha256Hex(userEntity.getPassword());
            System.out.println("前台传来的密码加密后是：" + MD5Password);

            //判断是否相同
            if (oldMD5Password.equals(MD5Password)) {
                System.out.println("密码校对成功 进行密码的修改操作");
                //相同 进行修改操作
                UserEntity u = new UserEntity();
                u.setUserId(userId);
                u.setPassword(DigestUtils.sha256Hex(userEntity.getNewPassword()));
                System.out.println("当前对象:" + u);
                userService.upadatePasswordOnLogin(u);

                Map<String, String> map = new HashMap<>();
                map.put(ConstantConfig.PUSH_TAG, "LOGIN");

                Jdpush.sendAliasPush(ConstantConfig.APP_KEY, ConstantConfig.MASTER_SECRET,
                        userId + "", "安全提醒 : 您的账号密码已经修改,请重新登录", map);




                return R.ok("密码修改成功", 100);

            } else {
                //不相同 提示
                return R.error(101, "密码不相同，请重新输入");
            }
        }
        return R.error(101, "请填写旧密码");
    }


    /**
     * 通过验证码的发送修改密码password   比对前台传的验证码和短信平台发送的验证码
     *
     * @return
     */
    @PostMapping("forgetPassword")
    @ApiOperation("非登录状态下修改密码/找回密码功能/忘記密碼功能")
    public R updatePasswordNoLogin(@RequestBody UserEntity userEntity) {

        //判断数据库中是否注册过本用户
        Long id = userService.getUserIdByMobile(userEntity.getMobile());
        userService.sendSms(userEntity.getMobile());
        if (id != null) {
            //System.out.println("数据库中有此用户，进行验证码比对方法");
            //发送验证码 比对验证码  codeInSQL是数据库中的验证码
            String codeInSQL = userService.getCodeByMobile(userEntity.getMobile());
            if (userEntity.getNewCode().equals(codeInSQL)) {   //获取前台传来的验证码
                //验证码比对成功 修改手机号用户的密码
                // UserEntity user = userService.getUserByUserId(id);   //找到
                UserEntity u = new UserEntity();
                u.setUserId(id);
                u.setPassword(DigestUtils.sha256Hex(userEntity.getNewPassword()));
                userService.upadatePasswordOnLogin(u);
                return R.ok("密码修改成功!", 100);
            }
            return R.error(101, "验证码输入有误！");
        }
        return R.error(101, "不存在此用户，请注册后使用！");
    }


    /**
     * 获取个人用户信息
     *
     * @return
     */
    @PostMapping("getUserByToken")
    @Login
    @ApiOperation("获取个人用户信息")
    public R getUserByToken(@RequestBody UserEntity userEntity) {
        Long userId = tokenService.getUserIdByToken(userEntity.getToken());
        UserEntity user = userService.getUserByUserId(userId);
        return R.ok("个人信息获取成功！", 100).put("data", user);
    }


    /**
     * 过滤敏感字符
     * @param str
     * @return
     */
    /*@PostMapping("wordFilter")
    @ApiOperation("过滤敏感字符")
    public String wordFilter(@RequestBody String str){
        SensitiveWordFilter sw = new SensitiveWordFilter();
//        SensitiveWordFilter sw = new SensitiveWordFilter("CensorWords.txt");
        sw.InitializationWork();
        long startNumer = System.currentTimeMillis();
        System.out.println("被检测字符长度:" + str.length());
        str = sw.filterInfo(str);
        long endNumber = System.currentTimeMillis();
        System.out.println("耗时(毫秒):" + (endNumber - startNumer));
        System.out.println("过滤之后:" + str);
        return str;
    }*/


    /**
     * 获取所有的职业
     */
    @GetMapping("getWork")
    @Login
    public R getWork(@ApiIgnore @RequestAttribute("userId") Long userId ){
        List list = userService.getWork();
        UserEntity userEntity = userService.getUserByUserId(userId);
        String myWork = userEntity.getWork();
        if(null == myWork){
            myWork = "";
        }
        return R.ok("",100).put("data",list).put("myWork",myWork);
    }

    /**
     * 修改用户数据
     */
    @PostMapping("updateUserWorkAndLable")
    @Login
    public R updateUserWork(@ApiIgnore @RequestAttribute("userId") Long userId,@RequestBody Map map ){
        map.put("userId",userId);
        userService.updateUserWork(map);
        return R.ok("",100);
    }


    /**
     *返回传来的标签在数据库的索引值（在数据库是第几个）
     */
    public R getMyLableId(String str){
        List lableList = userService.getLable();
        List list = new ArrayList();
        if(str != null){
            //这个人有标签
            String[] personalLables = str.split(",");
            if(personalLables.length>=1){
                //这个人有多个标签
                for(int s = 0;s<personalLables.length;s++){
                    for(int i = 0;i<lableList.size();i++){
                        if(personalLables[s].equals(lableList.get(i))){
                            list.add(i+1);
                        }
                    }
                }
            }else {
                for(int i = 0;i<lableList.size();i++){
                    if(personalLables[0].equals(lableList.get(i))){
                        list.add(i+1);
                    }
                }
            }
        }
        else{
            return R.ok("",100).put("myLable",list);
        }
        return R.ok("",100).put("myLable",list);
    }

    /**
     * 获取所有标签信息
     */
    @GetMapping("getLable")
    @Login
    public R getLable(@ApiIgnore @RequestAttribute("userId") Long userId){
        List list = userService.getLable();
        UserEntity userEntity = userService.getUserByUserId(userId);
        String myLable = userEntity.getPersonalLable();
        if(null == myLable){
            myLable  = "";
        }
        return R.ok("",100).put("data",list).put("myLable",myLable);
    }
}
